package cn.wtg.kotlinlib.net.downloadAndUpload.download

import okhttp3.Interceptor.Chain
import kotlin.Throws
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException

/**
 * author: wtg  2019/9/2 0002
 * desc: 下载的拦截器
 */
class DownloadInterceptor : Interceptor {
    private var downloadListener: DownloadResponseBody.DownloadListener?
    private var startPoint: Long = -1

    constructor(downloadListener: DownloadResponseBody.DownloadListener?) {
        this.downloadListener = downloadListener
    }

    constructor(downloadListener: DownloadResponseBody.DownloadListener?, startPoint: Long) {
        this.downloadListener = downloadListener
        this.startPoint = startPoint
    }

    @Throws(IOException::class)
    override fun intercept(chain: Chain): Response {
        val response: Response = chain.proceed(chain.request())
        return if (startPoint == -1L) {
            response.newBuilder().body(
                DownloadResponseBody(response.body, downloadListener)
            ).build()
        } else {
            response.newBuilder().body(
                DownloadResponseBody(response.body, downloadListener, startPoint)
            ).build()
        }
    }
}